package main

import (
	"fmt"
	"net"
	"os"
	"strconv"
	"strings"
	"time"
)

// 注意使用 telnet 127.0.0.1 7777
func main() {
	service := ":7777"
	tcpAddr, err := net.ResolveTCPAddr("tcp4", service)
	checkError2(err)
	listener, err := net.ListenTCP("tcp", tcpAddr)
	checkError2(err)
	for {
		conn, err := listener.Accept()
		if err != nil {
			continue
		}
		// 仅支持单任务
		//daytime := time.Now().String()
		//conn.Write([]byte(daytime)) // don't care about return value
		//conn.Close()                // we're finished with this client
		// 支持多任务
		go handleClient(conn)
	}
}
func handleClient(conn net.Conn) {
	//defer conn.Close()
	//daytime := time.Now().String()
	//conn.Write([]byte(daytime)) // don't care about return value
	conn.SetReadDeadline(time.Now().Add(2 * time.Minute))
	request := make([]byte, 128)
	defer conn.Close()
	for {
		readLen, err := conn.Read(request)
		if err != nil {
			fmt.Println(err)
			break // connection already closed by client
		}
		if strings.TrimSpace(string(request[:readLen])) == "exit" {
			break
		} else if strings.TrimSpace(string(request[:readLen])) == "timestamp" {
			daytime := strconv.FormatInt(time.Now().Unix(), 10)
			conn.Write([]byte(daytime))
		} else {
			daytime := time.Now().String()
			conn.Write([]byte(daytime))
		}
		request = make([]byte, 128) // clear last read content
	}

}
func checkError2(err error) {
	if err != nil {
		fmt.Fprintf(os.Stderr, "Fatal error: %s", err.Error())
		os.Exit(1)
	}
}
